package com.example.demo.web;

import com.example.demo.data.StaticData;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xiongyu
 * @create 2018/1/10
 */
@RestController
public class IndexAction {

    @Value("${score}")
    private int score;

    @Value("${sleepTime}")
    private long sleepTime;

    // 状态
    private static Boolean STATUS = Boolean.TRUE;
    // 返回结果码
    private static List<String> RESULT_CODES = new ArrayList<String>();
    // 请求
    private static Map<Integer, String> REQUEST = new HashMap<Integer, String>();


    @RequestMapping(value = "index", method = RequestMethod.GET)
    public String gotoIndex(@RequestParam int reqNo, @RequestParam String token) {
        String result = "200";
        System.out.println("请求号：" + reqNo);
        if (!REQUEST.containsKey(reqNo) || (REQUEST.containsKey(reqNo) && !REQUEST.get(reqNo).equals("200") && !REQUEST.get(reqNo).equals("400"))) {
            // 状态可用时
            if (STATUS) {
                try {
                    //TODO 线程池中获取线程（线程池配置20个线程），获取到返回成功，获取失败返回限流
                    Thread.sleep(sleepTime);
                }catch (Exception ex){
                    ex.printStackTrace();
                }
            } else {
                // 状态不可用
                result = "500";
                System.out.println(reqNo+"状态不可用！");
            }
        } else {
            // 重复请求
            result = "400";
            System.out.println( reqNo + "重复请求！");
        }
        // 保存处理结果
        RESULT_CODES.add(result);
        REQUEST.put(reqNo, result);
        return result;
    }

    @RequestMapping(value = "update", method = RequestMethod.GET)
    public String updateStatus(@RequestParam String status) {
        STATUS = Boolean.valueOf(status);
        return "当前状态为：" + STATUS.toString();
    }

    @RequestMapping(value = "result", method = RequestMethod.GET)
    public String showResult() {
        // 总分
        int sum = 0;
        for (String code : RESULT_CODES) {
            if (code.equals("200")) {
                sum += score;
            } else {
                sum += StaticData.SCORE.get(code);
            }
        }
        return String.valueOf(sum);
    }

    @RequestMapping(value = "clear", method = RequestMethod.GET)
    public String clear(){
        RESULT_CODES.clear();
        REQUEST.clear();
        return "清除成功！";
    }
}
